interface Record {
  initialAmount: string;
  balance: string;
  orderNo: string;
  reason: string;
}

Page({
  data: {
    tabs: ['充值', '充值记录', '扣费记录'],
    amounts: ['1', '5', '10', '20'],
    currentTab: 0,
    selectedAmount: '',
    chargeRecords: [
      {
        initialAmount: '0',
        balance: '5',
        orderNo: 'CZ20240120001',
        reason: '余额充值'
      },
      {
        initialAmount: '5',
        balance: '15',
        orderNo: 'CZ20240119002',
        reason: '余额充值'
      }
    ] as Record[],
    deductionRecords: [
      {
        initialAmount: '5',
        balance: '4',
        orderNo: 'DD20240115001',
        reason: '找车订单违约扣除'
      },
      {
        initialAmount: '10',
        balance: '8',
        orderNo: 'DD20240114002',
        reason: '订单超时违约扣除'
      },
      {
        initialAmount: '15',
        balance: '12',
        orderNo: 'DD20240113003',
        reason: '服务质量违约扣除'
      }
    ] as Record[]
  },

  onLoad() {
    // Initialize page data
    this.fetchUserBalance();
    this.fetchRecordHistory();
  },

  fetchUserBalance() {
    // In a real app, this would fetch the user's current balance from the server
    console.log('Fetching user balance...');
  },

  fetchRecordHistory() {
    // In a real app, this would fetch charge and deduction records from the server
    console.log('Fetching record history...');
    
    // Example of how to update records after fetching
    // this.setData({
    //   chargeRecords: fetchedChargeRecords,
    //   deductionRecords: fetchedDeductionRecords
    // });
  },

  // Navigation tab switching
  switchTab(event: WechatMiniprogram.TouchEvent) {
    const index = event.currentTarget.dataset.index as number;
    this.setData({ currentTab: index });
  },

  // Recharge content methods
  selectAmount(event: WechatMiniprogram.TouchEvent) {
    const amount = event.currentTarget.dataset.amount as string;
    this.setData({ selectedAmount: amount });
  },

  handleRecharge() {
    if (!this.data.selectedAmount) {
      wx.showToast({
        title: '请选择充值金额',
        icon: 'none'
      });
      return;
    }
    
    // Process recharge logic
    wx.showLoading({ title: '处理中' });
    
    // Simulate API call for payment and recharge
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: '充值成功',
        icon: 'success'
      });
      
      // Add to records and refresh
      const amount = this.data.selectedAmount;
      const newRecord = {
        initialAmount: this.getCurrentBalance(),
        balance: (Number(this.getCurrentBalance()) + Number(amount)).toString(),
        orderNo: 'CZ' + new Date().getTime().toString().slice(-8),
        reason: '余额充值'
      };
      
      const chargeRecords = [newRecord, ...this.data.chargeRecords];
      this.setData({ 
        chargeRecords,
        selectedAmount: '' // Reset selection after successful recharge
      });
    }, 1500);
  },

  // Records content methods
  copyOrderNo(event: WechatMiniprogram.TouchEvent) {
    const orderNo = event.currentTarget.dataset.orderNo as string;
    wx.setClipboardData({
      data: orderNo,
      success() {
        wx.showToast({
          title: '复制成功',
          icon: 'success',
          duration: 2000
        });
      }
    });
  },

  getCurrentBalance(): string {
    // In a real app, this would get the current balance from user data
    // Here we'll just use the most recent record's balance or default to '0'
    const records = [...this.data.chargeRecords, ...this.data.deductionRecords];
    if (records.length === 0) return '0';
    
    records.sort((a, b) => {
      // Sort by order number, assuming newer orders have higher numbers
      return b.orderNo.localeCompare(a.orderNo);
    });
    
    return records[0].balance;
  }
});
